﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestTasks.ThreadConsistency
{
    public static class Transfers
    {
        const string ERROR = "The 'from' account doesn't have enough funds";
        
        public static void Transfer(IAccount from, IAccount to, int amount)
        {
            if (from == null) throw new ArgumentNullException("from");
            if (to == null) throw new ArgumentNullException("to");
            if (amount < 0) throw new ArgumentOutOfRangeException("amount");

            if (amount == 0) return;

            Action action = delegate {
                if (!from.Withdraw(amount)) throw new ArgumentException("from", ERROR);
                to.Deposit(amount);
            };

            if (from.CompareTo(to) < 0) lock (from) lock (to) action();
            if (from.CompareTo(to) > 0) lock (to) lock (from) action();
        }
    }
}
